<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus">
          <el-option
            v-for="dict in dict.type.taskstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetime"
          placeholder="选择日期时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['task:reports:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['monitor:reports:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
        >清空</el-button>
      </el-col>
      <right-toolbar @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="tasksList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column type="index" label="编号" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="名称" align="center" width="80" prop="taskName" />
      <el-table-column label="类型" align="center" prop="jobType">
        <template slot-scope="scope">
          <div v-for="dict in dict.type.all_tasktype" :key="dict.value">
            <!-- {{ dict.value ==  ? dict.label : "" }} -->
            {{ dict.value == scope.row.jobType ? dict.label : "" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="任务状态"
        width="140"
        align="center"
        prop="taskStatus"
      >
        <template slot-scope="scope">
          <span v-for="dict in dict.type.taskstatus" :key="dict.value">
            <span v-if="scope.row.taskStatus == dict.value">
              {{ dict.label }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="140" align="center" prop="createTime" />
      <el-table-column label="结束时间" width="140" align="center" prop="endTime" />
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="耗时" align="center" prop="timeConsuming">
        <template slot-scope="scope">
          <span>{{ scope.row.timeConsuming }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleTaskResult(scope.row)"
            v-hasPermi="['console:dataTaskconf:execute']"
            v-if="type == 'dataTaskconf'"
            >结果</el-button
          > -->
          <el-button
            v-if="scope.row.jobType !== 'SYNC_DATA'"
            v-hasPermi="['console:tasks:details']"
            size="mini"
            type="text"
            @click="handelViewDetails(scope.row)"
          >详情</el-button>
          <el-button
            v-hasPermi="['console:tasks:resultLog']"
            size="mini"
            type="text"
            @click="handleResultLog(scope.row)"
          >日志</el-button>

          <el-button
            v-hasPermi="['console:dataTaskLog:remove']"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <el-dialog
      title="提示"
      :visible.sync="isLog"
      width="30%"
      :before-close="handleClose"
    >
      <div v-show="logFofText.length > 0" ref="logBox" class="textBox">
        <p
          v-for="(item, index) in logFofText"
          :key="index"
          :style="{ color: item.logLevel == 'error' ? 'red' : false }"
        >
          {{ item.text }}
        </p>
      </div>
      <el-empty
        v-show="logFofText.length < 1"
        description="暂无日志"
      />

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      v-if="asyncResultTable"
      title="结果"
      :visible.sync="asyncResult"
      width="75%"
      destroy-on-close
    >
      <div>
        <p>任务类型：{{ asyncResultTable.dataType }}</p>
        <p>任务信息：{{ asyncResultTable.message }}</p>
      </div>
      <el-table :data="asyncResultTable.items" height="300">
        <el-table-column label="对象名称" prop="objectName" />
        <el-table-column label="信息" prop="message" />
        <el-table-column label="堆栈错误信息" align="center" prop="errors">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['console:dataTaskconf:stack']"
              size="mini"
              type="text"
              @click="handleStack(scope.row)"
            >查看堆栈</el-button>
          </template>
        </el-table-column>
        <el-table-column label="对象类型" align="center" prop="type" />
        <el-table-column label="任务状态" align="center" prop="code">
          <template slot-scope="scope">
            <span v-for="dict in dict.type.taskstatus" :key="dict.value">
              <el-tag
                v-if="scope.row.code == dict.value"
                :type="dict.raw.listClass"
              >
                <!-- {{ scope.row.taskStatus }} -->
                {{ dict.label }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" />
        <el-table-column label="结束时间" align="center" prop="endTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['console:dataTaskconf:Repair']"
              size="mini"
              type="text"
              :disabled="scope.row.code == 2"
              @click="handleRepair(scope.row)"
            >修复</el-button>
            <el-button
              v-hasPermi="['console:tasks:check']"
              size="mini"
              type="text"
              :disabled="scope.row.code == 2"
              @click="handleCheck(scope.row)"
            >校验</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="asyncResult = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步结果"
      :visible.sync="codeEditorOpen"
      width="80%"
      destroy-on-close
    >
      <div class="codeBox">
        <div class="left">
          <el-divider content-position="left"><h2>源DDL</h2></el-divider>
          <codeEditor
            :editor-hight="250"
            :read-only="true"
            :code-data="codeEditor.sourceCode"
          />
        </div>
        <div class="line">
          <svg
            t="1722844374330"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="7388"
            width="50"
            height="50"
          >
            <path
              d="M938.666667 512L640 761.6V262.4z"
              fill="#8a8a8a"
              p-id="7389"
            />
            <path
              d="M128 426.666667h576v170.666666H128z"
              fill="#8a8a8a"
              p-id="7390"
            />
          </svg>
        </div>
        <div class="right">
          <el-divider content-position="left"><h2>目标DDL</h2></el-divider>
          <codeEditor
            ref="codeEditor"
            :editor-hight="250"
            :code-data="codeEditor.sinkCode"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-loading="repairLoading"
          type="primary"
          @click="handleRunDll"
        >修 复</el-button>
        <el-button
          type="primary"
          @click="codeEditorOpen = false"
        >取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      v-if="stackErrorsMsg"
      title="堆栈错误信息"
      :visible.sync="dialogStackVisible"
      width="75%"
    >
      <pre><code>{{ stackErrorsMsg }}</code></pre>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogStackVisible = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dataTaskJobList, dataTaskLogGetInfo } from '@/api/console/tasks'
import { delDataTaskLog } from '@/api/console/dataTaskLog'
import { sqlTaskExecuteSql } from '@/api/console/executeSql'
import { delDataTaskconfVerify } from '@/api/console/dataTaskconf'
import codeEditor from '@/components/CodeEditor/index.vue'

export default {
  name: 'Tasks',
  dicts: [
    'appraise_countmode',
    'appraise_taskmode',
    'all_tasktype',
    'taskstatus',
    'sys_job_status'
  ],
  components: { codeEditor },

  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评估任务表格数据
      tasksList: [],
      // 弹出层标题
      title: '查看详情',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        taskStatus: null,
        createTime: null,
        taskName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      region: '',
      dataObj: {},
      childTableData: [],
      isLog: false,
      logFofText: [],
      timer: null,
      currentIndex: 0,
      type: null,
      asyncResultTable: null,
      asyncResult: false,
      codeEditor: {
        sourceCode: '',
        sinkCode: ''
      },
      codeEditorOpen: false,
      dialogStackVisible: false,
      verifyData: null,
      repairLoading: false,
      jobType: null,
      stackErrorsMsg: null
    }
  },
  created() {
    this.type = this.$route.query.type
    this.jobType = this.$route.query.jobType
    this.getList()
  },
  methods: {
    handleEdit(row) {
      this.$alert(row.ddlSql, 'ddlsql', {
        confirmButtonText: '确定'
      })
    },
    handleStack(row) {
      if (!row.errors) {
        return this.$message.warning('暂无错误信息')
      }
      this.dialogStackVisible = true
      this.stackErrorsMsg = row.errors
    },
    async handleTaskResult(row) {
      this.verifyData = row
      this.asyncResult = true
      const res = await dataTaskLogGetInfo({
        id: row.id
      })
      const tableData = JSON.parse(res.data.taskResult)
      this.asyncResultTable = tableData
      if (tableData.items.length > 0) {
        return
      }
      const newTableData = []
      Object.keys(tableData.data).forEach((f) => {
        tableData.data[f].items.forEach((j) => {
          newTableData.push({
            ...j,
            taskType: f
          })
        })
      })
      this.asyncResultTable.items = newTableData
    },

    getList() {
      this.loading = true
      if (!this.$route.query.id || !this.$route.query.jobType) {
        return this.$message.error('参数错误')
      }
      dataTaskJobList({
        taskId: this.$route.query.id,
        jobType: this.$route.query.jobType,
        ...this.queryParams
      }).then((response) => {
        this.tasksList = response.rows
        this.total = response.total
        this.loading = false
      })
      return
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskType: null,
        id: null,
        databaseName: null,
        taskWay: null,
        taskCount: null,
        taskMode: null,
        taskTables: null,
        taskStatus: null,
        strategy: null,
        desc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.startNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const { id, jobType } = this.$route.query
      this.$modal
        .confirm('是否确认删除日志序号为"' + ids + '"的数据项？')
        .then(function() {
          return delDataTaskLog({
            taskId: id,
            jobType,
            idArray: Array.isArray(ids) ? ids : [ids]
          })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
    },
    /** 清空按钮操作 */
    handleClean() {
      const { id, jobType } = this.$route.query
      this.$modal
        .confirm('是否确认清空所有操作日志数据项？')
        .then(function() {
          return delDataTaskLog({
            taskId: id,
            jobType,
            idArray: null
          })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('清空成功')
        })
        .catch(() => {})
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 执行报告 */
    async handleResultLog(row) {
      this.isLog = true
      const that = this
      const res = await dataTaskLogGetInfo({
        id: row.id
      })
      const LogText = JSON.parse(res.data.taskLog)
      if (!LogText) {
        return (this.logFofText = false)
      }
      this.logFofText = []
      LogText.forEach((f) => {
        this.logFofText.push({
          text: `${f.time}：${f.logMsg}`,
          logLevel: f.logLevel
        })
      })
      this.$nextTick(() => {
        const scrollElem = that.$refs.logBox
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: 'smooth'
        })
      })
    },
    handleClose() {
      clearInterval(this.timer)
      this.timer = null
      this.isLog = false
    },
    /** 查看详情 */
    handelViewDetails(row) {
      if (row.taskStatus != 2) {
        return this.$message.warning('任务未成功')
      }
      const type = this.$route.query.type
      let path
      if (type == 'check') path = `/report/verificationReport?id=${row.id}`
      if (type == 'reports') path = `/report/assessmentReport?id=${row.id}`
      if (type == 'dataTaskconf') path = `/report/migrationReport?taskId=${this.$route.query.id}&&id=${row.id}`

      window.open(path)
    },
    async handleRepair(row) {
      this.codeEditorOpen = true
      this.codeEditor.sourceCode = row.sourceDdl
      this.codeEditor.sinkCode = row.sinkDdl || ''
    },
    async handleRunDll() {
      this.repairLoading = true
      try {
        const res = await sqlTaskExecuteSql({
          datasourceId: this.verifyData.id,
          sqlContext: this.$refs.codeEditor._data.content
        })
        this.$message.error('修复成功')
        this.repairLoading = false
        this.codeEditorOpen = false
      } catch (error) {
        this.$message.error(error)
        this.repairLoading = false
      }
    },
    handleCheck(row) {
      const that = this
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认校验配置编号为"' + that.verifyData.id + '"的数据项？')
        .then(function() {
          return delDataTaskconfVerify({
            id: that.verifyData.id,
            taskTypeScope: row.type,
            name: row.objectName
          })
        })
        .then(() => {
          // this.getList();
          this.$modal.msgSuccess('校验成功')
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  padding: 0;
}

.divider {
  margin: 0px;
}

.viewDetail {
  padding: 5px 20px;

  .objTitle {
    font-size: 15px;
    font-weight: 600;
    .objParams {
      font-weight: 400;
    }
  }
}
.textBox {
  height: 350px;
  overflow: auto;
}

.codeBox {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .left,
  .right {
    width: 45%;
  }

  .line {
    width: 5%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

h2 {
  margin: 0;
}

pre {
  height: 400px;
  overflow: auto;
}
</style>
